import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/order_dao.dart';
import 'package:flutter_taotaoshipin/util/events.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

/// iOS支付单一实例
final applePayUtils = ApplePayUtils();

class ApplePayUtils {
  /// 单例模式
  static final ApplePayUtils _payUtils =
      ApplePayUtils.init();

  factory ApplePayUtils() {
    return _payUtils;
  }

  ApplePayUtils.init() {
    _initStoreInfo();
  }

  /// 初始化商店信息
  Future<void> _initStoreInfo() async {
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      return;
    }

    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());

      // 开局监听
      var transactions = await SKPaymentQueueWrapper().transactions();
      if (transactions.isNotEmpty) {
        print('有未处理的订单：${transactions.length}');
      }
    }
  }

  // 内购买
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _pruchaseSubscription;

  bool showLoading = false;

  /// 开始订阅
  void startSubscription() {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _pruchaseSubscription =
        purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _pruchaseSubscription.cancel();
    }, onError: (Object error) {
      print(error);
    });
  }

  /// 开始支付
  Future<void> startApplePay(String productId, String uuid) async {
    EasyLoading.show(status: '正在支付');

    // 先补单
    await _checkPendingPurchase();

    // 请求商品信息
    print('IAP：开始请求商品');
    var response =
        await InAppPurchase.instance.queryProductDetails({productId});
    if (response.error != null) {
      print('IAP: 请求商品错误：${response.error!.message}');
      EasyLoading.showError('请求商品错误');
      return;
    }
    if (response.productDetails.isEmpty) {
      print('IAP：商品ID不存在');
      EasyLoading.showError('商品ID不存在');
      return;
    }

    print('IAP：开始购买商品');
    var purchaseParam = PurchaseParam(
        productDetails: response.productDetails.first,
        applicationUserName: uuid);

    try {
      await InAppPurchase.instance.buyConsumable(purchaseParam: purchaseParam);
    } catch (e) {
      print('IAP：$e');
      EasyLoading.showError('存在相同订单在处理，请再试一次');
    } finally {
      // 进入支付流程
      showLoading = true;
    }
  }

  /// 检查补单
  Future<void> _checkPendingPurchase() async {
    print('IAP：检查补单');
    final paymentWrapper = SKPaymentQueueWrapper();
    final transactions = await paymentWrapper.transactions();

    await Future.forEach(transactions, (transaction) async {
      if (transaction.transactionState ==
              SKPaymentTransactionStateWrapper.purchased ||
          transaction.transactionState ==
              SKPaymentTransactionStateWrapper.restored) {
        // 已支付订单和恢复购买订单
        try {
          // 新版不需要票据
          var receipt_data = '';
          var result = await OrderDao.appleReceipt(
            receipt_data,
            transaction.transactionIdentifier ?? '',
          );
          if (result.code == 0) {
            // 请求结果成功，数据不为空
            if (result.data != null) {
              if (result.data!.transactionId ==
                  transaction.transactionIdentifier) {
                // 结束订单
                await paymentWrapper.finishTransaction(transaction);
              } else {
                print('transactionId不一致');
              }
            } else {
              print('数据为空');
            }
          } else {
            print(result.message);
          }
        } on HiNetError catch (e) {
          print(e.message);
        } catch (e) {
          print(e.toString());
        }
      } else {
        // 其他状态订单直接结束
        await paymentWrapper.finishTransaction(transaction);
      }
    });
  }

  /// 监听支付状态
  Future<void> _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        print('IAP: 正在支付');
      } else if (purchaseDetails.status == PurchaseStatus.error) {
        print('IAP: 支付错误');
        EasyLoading.showError('支付错误');
        // 结束
        await _inAppPurchase.completePurchase(purchaseDetails);
      } else if (purchaseDetails.status == PurchaseStatus.purchased ||
          purchaseDetails.status == PurchaseStatus.restored) {
        print('IAP: 支付成功');
        EasyLoading.dismiss();
        await _verifyPurchase(purchaseDetails);
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        print('IAP: 支付取消');
        EasyLoading.showError('支付取消');
        // 结束
        await _inAppPurchase.completePurchase(purchaseDetails);
        // 通知取消
        _notifyPayResult(ApplePayResult(
          status: 'canceled',
          orderId: '',
          transactionId: '',
        ));
      } else {
        print('IAP: 支付状态未知');
      }
    }
  }

  /// 校验订单
  Future<void> _verifyPurchase(PurchaseDetails purchaseDetails) async {
    AppController appController = Get.find();
    var orderId = appController.applePayInfo.orderId ?? '';
    var uuid = appController.applePayInfo.uuid ?? '';
    try {
      if (showLoading) {
        EasyLoading.show(status: '正在验证');
      }
      // 新版不需要票据
      var receipt_data = '';
      var result = await OrderDao.appleReceipt(
        receipt_data,
        purchaseDetails.purchaseID ?? '',
        orderId: orderId,
        uuid: uuid,
      );
      if (result.code == 0) {
        // 请求结果成功，数据不为空
        if (result.data != null) {
          if (result.data!.transactionId == purchaseDetails.purchaseID) {
            if (showLoading) {
              EasyLoading.showSuccess('支付成功');
            }
            if (purchaseDetails.pendingCompletePurchase) {
              print('IAP: 结束支付队列');
              await _inAppPurchase.completePurchase(purchaseDetails);
            }
            // 通知成功
            _notifyPayResult(ApplePayResult(
              status: 'success',
              orderId: result.data!.orderId!,
              transactionId: result.data!.transactionId!,
            ));
          } else {
            if (showLoading) {
              EasyLoading.dismiss();
            }
          }
        } else {
          if (showLoading) {
            EasyLoading.dismiss();
          }
        }
      } else {
        if (showLoading) {
          EasyLoading.dismiss();
        }
      }
    } on HiNetError catch (e) {
      if (showLoading) {
        EasyLoading.dismiss();
      }
    } catch (e) {
      if (showLoading) {
        EasyLoading.dismiss();
      }
    } finally {
      showLoading = false;
    }
  }

  /// 通知支付结果
  void _notifyPayResult(ApplePayResult result) {
    eventBus.fire(result);
  }

  /// 恢复购买
  Future<void> restorePurchase() async {
    try {
      EasyLoading.show();
      await _inAppPurchase.restorePurchases();
      EasyLoading.showSuccess('恢复完成');
    } catch (_)  {
      EasyLoading.showError('恢复失败');
    }
  }

  /// 确认价格更改
  Future<void> confirmPriceChange(BuildContext context) async {
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iapStoreKitPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iapStoreKitPlatformAddition.showPriceConsentIfNeeded();
    }
  }
}

/// Example implementation of the
/// [`SKPaymentQueueDelegate`](https://developer.apple.com/documentation/storekit/skpaymentqueuedelegate?language=objc).
///
/// The payment queue delegate can be implementated to provide information
/// needed to complete transactions.
class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}
